<template>
  <el-config-provider :locale="zhCn">
    <div class="my-orders-page">
      <!-- 订单页面头部 -->
      <div class="page-header bg-gradient-to-r from-blue-50 to-purple-50 py-6 px-4 rounded-lg mb-6">
        <h1 class="text-2xl font-bold text-gray-800 mb-2">我的订单</h1>
        <p class="text-gray-500">查看并管理您的所有订单</p>
      </div>

      <!-- 订单分类标签页 -->
      <el-card class="mb-6 border-0 rounded-lg shadow-sm">
        <el-tabs v-model="activeTab" class="order-tabs" @tab-change="handleTabChange">
          <el-tab-pane label="全部订单" name="all">
            <template #label>
              <div class="tab-label">
                <span>全部订单</span>
                <el-badge :value="orderCounts.all" class="ml-2" type="info" v-if="orderCounts.all > 0" />
              </div>
            </template>
          </el-tab-pane>
        </el-tabs>
        
        <!-- 过滤状态提示 -->
        <div v-if="remarkFilter" class="filter-status px-4 py-2 bg-blue-50 border-t border-blue-100">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <el-icon class="mr-2 text-blue-600"><InfoFilled /></el-icon>
              <span class="text-sm text-blue-700">
                当前筛选：{{ getRemarkFilterText(remarkFilter) }}
              </span>
            </div>
            <el-button 
              type="text" 
              size="small" 
              @click="clearRemarkFilter"
              class="text-blue-600 hover:text-blue-800"
            >
              清除筛选
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 搜索筛选区域 -->
      <div class="search-filter flex items-center justify-between mb-6 flex-wrap gap-4">
        <el-input
          v-model="searchKeyword"
          placeholder="输入订单号或商品名称搜索"
          class="max-w-xs"
          clearable
          @change="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <div class="filter-actions flex items-center space-x-3">
          <el-select v-model="timeRange" placeholder="选择时间范围" class="w-40">
            <el-option label="最近三个月" value="3months" />
            <el-option label="今年内" value="thisYear" />
            <el-option label="去年" value="lastYear" />
            <el-option label="全部时间" value="all" />
          </el-select>
          
          <el-select v-model="remarkFilter" placeholder="订单状态" class="w-36" clearable>
            <template #prefix>
              <el-icon><InfoFilled /></el-icon>
            </template>
            <el-option label="全部订单" value="">
              <div class="flex items-center">
                <el-icon class="mr-2"><Document /></el-icon>
                <span>全部订单</span>
              </div>
            </el-option>
            <el-option label="已开票" value="已开票">
              <div class="flex items-center">
                <el-icon class="mr-2 text-green-500"><Check /></el-icon>
                <span>已开票</span>
              </div>
            </el-option>
            <el-option label="已出库" value="已出库">
              <div class="flex items-center">
                <el-icon class="mr-2 text-blue-500"><Box /></el-icon>
                <span>已出库</span>
              </div>
            </el-option>
          </el-select>
          
          <el-button type="primary" plain @click="handleSearch">筛选</el-button>
        </div>
      </div>

      <!-- 订单列表 -->
      <template v-if="filteredOrders.length > 0">
        <div class="orders-list space-y-6">
          <el-card 
            v-for="order in filteredOrders" 
            :key="order.id" 
            class="order-item border-0 rounded-lg overflow-hidden transform transition-all duration-300 hover:shadow-md hover:-translate-y-1"
            :class="getOrderCardClass(order)"
          >
            <!-- 订单头部信息 -->
            <div class="order-header p-4 border-b bg-gradient-to-r from-gray-50 to-blue-50" :class="getOrderHeaderClass(order)">
              <!-- 订单标题 -->
              <div class="order-title mb-3">
                <h3 class="text-lg font-bold text-gray-800 flex items-center" :class="{ '!text-red-500 !line-through bg-none': !canDeleteOrder(order) }">
                  <el-icon class="mr-2 text-blue-600"><ShoppingBag /></el-icon>
                  {{ order.title || getOrderTitle(order) }}
                  <span v-if="!canDeleteOrder(order)" class="text-red-500 ml-2">已经删除</span>
                </h3>
              </div>
              
              <!-- 订单基本信息 -->
              <div class="order-info flex items-center justify-between flex-wrap gap-4">
                <div class="flex items-center space-x-6 flex-wrap">
                  <div class="order-number flex items-center">
                    <el-icon class="mr-1 text-gray-400"><Document /></el-icon>
                    <span class="text-gray-500">订单编号：</span>
                    <span class="font-medium text-blue-600">{{ order.orderNum }}</span>
                  </div>
                  <div class="order-date flex items-center">
                    <el-icon class="mr-1 text-gray-400"><Clock /></el-icon>
                    <span class="text-gray-500">下单时间：</span>
                    <span>{{ formatOrderTime(order.createTime) }}</span>
                  </div>
                  <!-- 订单备注状态 -->
                  <div v-if="order.remark" class="order-remark flex items-center">
                    <el-icon class="mr-1 text-gray-400"><InfoFilled /></el-icon>
                    <span class="text-gray-500">订单状态：</span>
                    <el-tag 
                      :type="getRemarkTagType(order.remark)" 
                      size="small" 
                      effect="light"
                      class="ml-1"
                    >
                      {{ order.remark }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 订单商品列表 -->
            <div class="order-products">
              <div 
                v-for="product in order.goodsList" 
                :key="product.id" 
                class="product-item flex py-4 px-4 border-b last:border-b-0 hover:bg-gray-50"
                :class="{ 'deleted-product': product.deleteStatus === 1 }"
              >
                <div class="product-image w-20 h-20 flex-shrink-0 mr-4 relative">
                  <img 
                    :src="product.goodsInfo.mainPic || '/images/no.jpg'" 
                    :alt="product.goodsInfo.title" 
                    class="w-full h-full object-cover rounded border"
                    :class="{ 'opacity-50': product.deleteStatus === 1 }"
                    @error="handleImageError"
                  >
                  <!-- 删除标记 -->
                  <div v-if="product.deleteStatus === 1" class="absolute inset-0 bg-red-500 bg-opacity-20 rounded border-2 border-red-500 flex items-center justify-center">
                    <div class="bg-red-500 text-white px-2 py-1 rounded text-xs font-bold">已删除</div>
                  </div>
                </div>
                
                <div class="product-info flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <div>
                      <h3 class="product-name text-base font-medium text-gray-800" :class="{ 'line-through text-gray-400': product.deleteStatus === 1 }">
                        {{ product.goodsInfo.title }}
                        <span v-if="product.deleteStatus === 1" class="text-red-500 ml-2 text-sm">(已删除)</span>
                      </h3>
                      <div class="text-sm text-gray-500" :class="{ 'opacity-50': product.deleteStatus === 1 }">{{ product.goodsInfo.oracleGoodsName }}</div>
                    </div>
                    <div class="flex items-center gap-2">
                      <el-tag 
                        v-if="product.deleteStatus === 1"
                        type="danger" 
                        size="small" 
                        effect="light"
                        class="deleted-tag"
                      >
                        已删除
                      </el-tag>
                      <el-tag 
                        :type="getProductStatusType(product.goodsInfo.status)" 
                        size="small" 
                        effect="light"
                      >
                        {{ getProductStatusText(product.goodsInfo.status) }}
                      </el-tag>
                    </div>
                  </div>
                  
                  <div class="product-details grid grid-cols-2 gap-x-4 gap-y-2 text-sm" :class="{ 'opacity-50': product.deleteStatus === 1 }">
                    <div class="product-spec text-gray-600">
                      <span class="font-medium">规格：</span>
                      {{ product.goodsInfo.goodsSpec }}
                    </div>
                    <div class="product-code text-gray-600">
                      <span class="font-medium">商品编码：</span>
                      {{ product.goodsInfo.goodsCode }}
                    </div>
                    <div class="product-approval text-gray-600">
                      <span class="font-medium">批准文号：</span>
                      {{ product.goodsInfo.approvalNo }}
                    </div>
                    <div class="product-category text-gray-600">
                      <span class="font-medium">分类：</span>
                      {{ product.goodsInfo.gCategory }} - {{ product.goodsInfo.qCategory }}
                    </div>
                    <div class="product-formula text-gray-600">
                      <span class="font-medium">剂型：</span>
                      {{ product.goodsInfo.formula }}
                    </div>
                    <div class="product-stock text-gray-600">
                      <span class="font-medium">库存：</span>
                      <span :class="getStockStatusClass(isNearExpiryOrder(order) ? (product.goodsInfo.nearStorNum || product.goodsInfo.storNum) : product.goodsInfo.storNum)">
                        {{ getStockStatusText(isNearExpiryOrder(order) ? (product.goodsInfo.nearStorNum || product.goodsInfo.storNum) : product.goodsInfo.storNum) }}
                      </span>
                    </div>
                    <div class="product-manufacturer text-gray-600">
                      <el-icon class="mr-1"><Shop /></el-icon>
                      {{ product.goodsInfo.manufacturer }}
                    </div>
                  </div>
                </div>
                
                <div class="product-quantity-price flex flex-col items-end justify-center mr-6 min-w-[120px]" :class="{ 'opacity-50': product.deleteStatus === 1 }">
                  <div class="product-price-details text-right">
                    <div class="product-unit-price text-sm text-gray-500">
                      单价：{{ formatPriceAuth(isNearExpiryOrder(order) ? product.goodsInfo.nextValPrice : product.price, !!userStore.token, userStore.userInfo?.discount, order?.remark === '秒杀订单' ? 1 : product.goodsInfo?.noDiscounts) }}
                      <span v-if="userStore.userInfo?.discount && product.goodsInfo?.noDiscounts !== 1 && order?.remark !== '秒杀订单'" class="line-through">
                        {{ formatPriceAuth(isNearExpiryOrder(order) ? product.goodsInfo.nextValPrice : product.price, !!userStore.token) }}
                      </span>
                    </div>
                    <div v-if="product.discountPrice !== '0.00'" class="product-discount text-sm text-gray-500">
                      优惠：{{ formatPriceAuth(product.discountPrice, !!userStore.token) }}
                    </div>
                    <div class="product-total-price font-medium text-red-600 text-lg" :class="{ 'line-through text-gray-400': product.deleteStatus === 1 }">
                      {{ formatPriceAuth((isNearExpiryOrder(order) ? Number(product.goodsInfo.nextValPrice) : Number(product.price)) * product.count, !!userStore.token, userStore.userInfo?.discount, order?.remark === '秒杀订单' ? 1 : product.goodsInfo?.noDiscounts) }}
                      <span v-if="userStore.userInfo?.discount && product.goodsInfo?.noDiscounts !== 1" class="text-gray-500 text-sm line-through">
                        {{ formatPriceAuth((isNearExpiryOrder(order) ? Number(product.goodsInfo.nextValPrice) : Number(product.price)) * product.count, !!userStore.token) }}
                      </span>
                    </div>
                  </div>
                  <div class="product-quantity text-gray-500 mt-2">
                    x{{ product.count }}
                  </div>
                </div>
                
                <div class="product-actions flex flex-col items-center justify-center">
                  <el-button
                    v-if="order.goodsList.length > 1 && canDeleteProduct(product)"
                    type="danger"
                    size="small"
                    plain
                    class="delete-product-btn"
                    @click="handleDeleteOrderGoods(order.orderNum, product.goodsInfo.goodsId)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 订单底部信息 -->
            <div class="order-footer flex justify-between items-center p-4 bg-gradient-to-r from-blue-50 to-purple-50">
              <div class="order-total flex items-center">
                <div class="total-info">
                  <div class="flex items-center mb-1">
                    <el-icon class="mr-1 text-gray-400"><Box /></el-icon>
                    <span class="text-gray-600">共 {{ order.goodsList.reduce((sum, item) => sum + item.count, 0) }} 件商品</span>
                  </div>
                  <div class="flex items-center">
                    <span class="text-gray-600 mr-2">订单总计：</span>
                    <span class="text-xl text-red-600 font-bold">{{ formatPriceAuth(calculateOrderTotal(order), !!userStore.token, order?.remark === '秒杀订单' ? 1 : userStore.userInfo?.discount) }}</span>
                    <span v-if="userStore.userInfo?.discount && order?.remark !== '秒杀订单'" class="text-gray-500 text-sm line-through ml-2">
                      {{ formatPriceAuth(calculateOrderTotal(order), !!userStore.token) }}
                    </span>
                    <span v-if="order.discountPrice !== '0.00'" class="text-green-600 ml-2 text-sm">
                      (已优惠 {{ formatPriceAuth(order.discountPrice, !!userStore.token) }})
                    </span>
                  </div>
                </div>
              </div>
              
              <div class="order-actions flex flex-wrap gap-2">
                <el-button 
                  v-if="order.status === 1"
                  type="danger" 
                  plain 
                  size="small"
                  class="action-btn"
                >
                  <el-icon class="mr-1"><Close /></el-icon>
                  取消订单
                </el-button>
                <el-button 
                  v-if="canDeleteOrder(order)"
                  type="danger" 
                  plain 
                  size="small"
                  class="action-btn"
                  @click="handleDeleteOrder(order.orderNum)"
                >
                  <el-icon class="mr-1"><Delete /></el-icon>
                  删除订单
                </el-button>
                <el-button 
                  type="info" 
                  plain 
                  size="small"
                  class="action-btn"
                >
                  <el-icon class="mr-1"><View /></el-icon>
                  订单详情
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination flex justify-center my-8">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalOrders"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </template>

      <!-- 无订单展示 -->
      <el-empty 
        v-else 
        description="暂无相关订单" 
        :image-size="200"
      >
        <template #image>
          <div class="empty-image flex flex-col items-center">
            <el-icon :size="60" class="text-gray-300 mb-4"><ShoppingBag /></el-icon>
          </div>
        </template>
        <el-button type="danger" @click="goShopping">去购物</el-button>
      </el-empty>

      <!-- 支付弹框 -->
      <PaymentDialog
        v-model:visible="paymentDialogVisible"
        :order-number="currentPayOrderNumber"
        :amount="currentPayAmount"
        @payment-success="handlePaymentSuccess"
        @payment-cancel="handlePaymentCancel"
      />
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Shop, ShoppingBag, Document, Clock, Box, Close, View, Delete, InfoFilled, Check } from '@element-plus/icons-vue'
import { ElMessage, ElConfigProvider, ElMessageBox } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import PaymentDialog from '../components/PaymentDialog.vue'
import { getOrderList, getOrderCount } from '@/api/modules/cart'
import { deleteOrder, deleteOrderGoods } from '@/api/modules/order'
import { OrderListResponse } from '@/api/types'
import { useUserStore } from '@/stores/user'
import { getStockStatusText, getStockStatusClass } from '@/lib/stockUtils'
import { formatPriceAuth } from '@/lib/utils'

const router = useRouter()
const userStore = useUserStore()

// 标签页状态
const activeTab = ref('all')

// 分页状态
const currentPage = ref(1)
const pageSize = ref(5)
const totalOrders = ref(0)

// 搜索筛选状态
const searchKeyword = ref('')
const timeRange = ref('3months')
const remarkFilter = ref('') // 新增备注过滤器

// 订单数量统计
const orderCounts = reactive({
  all: 0,
  unpaid: 0,
  pending: 0,
  picked: 0,
  shipped: 0,
  delivering: 0,
  completed: 0
})

// 支付弹框状态
const paymentDialogVisible = ref(false)
const currentPayOrderNumber = ref('')
const currentPayAmount = ref(0)

// 使用接口类型改进订单数据
const orders = ref<OrderListResponse['data']['list']>([])

// 加载订单数据
const loadOrders = async () => {
  try {
    const [orderResponse, countResponse] = await Promise.all([
      getOrderList({
        page: currentPage.value,
        size: pageSize.value,
        remark: remarkFilter.value || undefined
      }),
      getOrderCount()
    ])
    
    if (orderResponse.code === 1000) {
      orders.value = orderResponse.data.list
      totalOrders.value = orderResponse.data.pagination.total
    } else {
      ElMessage.error(orderResponse.message || '获取订单列表失败')
    }

    if (countResponse.code === 1000) {
      // 更新订单数量统计
      orderCounts.unpaid = parseInt(countResponse.data['待付款']) || 0
      orderCounts.pending = parseInt(countResponse.data['待发货']) || 0
      orderCounts.picked = parseInt(countResponse.data['待收货']) || 0
      orderCounts.shipped = parseInt(countResponse.data['待评价']) || 0
      orderCounts.completed = parseInt(countResponse.data['交易完成']) || 0
      // 计算全部订单数量
      orderCounts.all = Object.values(countResponse.data).reduce((sum, count) => sum + (parseInt(count) || 0), 0)
    } else {
      ElMessage.error(countResponse.message || '获取订单数量统计失败')
    }
  } catch (error) {
    console.error('加载订单数据失败:', error)
    ElMessage.error('加载订单数据失败')
  }
}

// 计算筛选后的订单
const filteredOrders = computed(() => {
  let result = [...orders.value]
  
  // 按标签筛选
  if (activeTab.value !== 'all') {
    const statusMap: Record<string, number> = {
      'unpaid': 0,
      'pending': 1,
      'picked': 2,
      'shipped': 3,
      'delivering': 4,
      'completed': 4
    }
    result = result.filter(order => order.status === statusMap[activeTab.value])
  }
  
  // 按关键词搜索（前端过滤）
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(order => 
      order.orderNum.toLowerCase().includes(keyword) || 
      order.goodsList.some(p => p.goodsInfo.title.toLowerCase().includes(keyword))
    )
  }
  
  return result
})

// 事件处理函数
const handleTabChange = () => {
  currentPage.value = 1 // 切换标签时重置页码
  loadOrders()
}

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置页码
  loadOrders()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 改变每页条数时重置页码
  loadOrders()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadOrders()
}

const goShopping = () => {
  router.push('/')
}

// 处理支付成功
const handlePaymentSuccess = (paymentInfo: { orderNumber: string, paymentMethod: string }) => {
  ElMessage.success(`订单 ${paymentInfo.orderNumber} 支付成功！使用 ${getPaymentMethodName(paymentInfo.paymentMethod)}`)
  
  // 更新本地订单状态（实际应用中应该通过API更新）
  const orderIndex = orders.value.findIndex(o => o.orderNum === paymentInfo.orderNumber)
  if (orderIndex > -1) {
    orders.value[orderIndex].status = 1
  }
}

// 处理支付取消
const handlePaymentCancel = (orderNumber: string) => {
  console.log(`取消支付订单: ${orderNumber}`)
}

// 获取支付方式名称
const getPaymentMethodName = (method: string): string => {
  const methodMap: Record<string, string> = {
    'wechat': '微信支付',
    'alipay': '支付宝支付',
    'unionpay': '银联支付'
  }
  return methodMap[method] || method
}

// 获取订单备注标签类型
const getRemarkTagType = (remark: string): string => {
  if (remark === '已开票') {
    return 'success'
  } else if (remark === '已出库') {
    return 'info'
  }
  return 'info' // 默认类型
}

// 获取订单卡片样式类
const getOrderCardClass = (order: any): string => {
  if (order.remark === '已开票') {
    return 'order-invoiced'
  } else if (order.remark === '已出库') {
    return 'order-shipped'
  }
  return ''
}

// 获取订单头部样式类
const getOrderHeaderClass = (order: any): string => {
  if (order.remark === '已开票') {
    return 'header-invoiced'
  } else if (order.remark === '已出库') {
    return 'header-shipped'
  }
  return ''
}

// 获取备注过滤文本
const getRemarkFilterText = (remark: string): string => {
  if (remark === '已开票') {
    return '已开票订单'
  } else if (remark === '已出库') {
    return '已出库订单'
  }
  return remark
}

// 清除备注过滤
const clearRemarkFilter = () => {
  remarkFilter.value = ''
  handleSearch()
}

// 更新商品状态相关函数
const getProductStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '下架',
    1: '正常',
    2: '缺货',
    3: '停售'
  }
  return statusMap[status] || '未知状态'
}

const getProductStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[status] || ''
}

// 生成订单标题
const getOrderTitle = (order: OrderListResponse['data']['list'][0]): string => {
  if (order.goodsList.length === 1) {
    return order.goodsList[0].goodsInfo.title
  } else if (order.goodsList.length > 1) {
    return `${order.goodsList[0].goodsInfo.title} 等${order.goodsList.length}件商品`
  }
  return '订单详情'
}

// 格式化订单时间
const formatOrderTime = (timeString: string): string => {
  const date = new Date(timeString)
  // 如果时间显示少了8小时，说明服务器返回的是UTC时间，需要加上8小时转换为中国时区
  const chinaTime = new Date(date.getTime() + (8 * 60 * 60 * 1000))
  return chinaTime.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理图片错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  if (img) {
    img.src = '/images/no.jpg'
  }
}

// 计算订单总价（考虑商品折扣）
function calculateOrderTotal(order: any) {
  return order.goodsList.reduce((total: number, product: any) => {
    const price = isNearExpiryOrder(order) ? Number(product.goodsInfo.nextValPrice) : Number(product.price)
    const count = product.count
    return total + price * count
  }, 0)
}

// 在 script setup 部分添加新的函数
const isNearExpiryOrder = (order: any): boolean => {
  return order.title === '近效期订单'
}

// 判断是否可以删除订单
const canDeleteOrder = (order: any): boolean => {
  // deleteStatus 为 1 表示已删除，0 表示可以删除
  return order.goodsList.some((p: any) => p.deleteStatus === 0)
}

// 判断是否可以删除商品
const canDeleteProduct = (product: any): boolean => {
  // deleteStatus 为 1 表示已删除，0 表示可以删除
  return product.deleteStatus === 0
}

// 删除订单中的商品
const handleDeleteOrderGoods = async (orderNum: string, goodsId: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个商品吗？删除后将无法恢复',
      '删除商品',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    const response = await deleteOrderGoods({ orderNum, goodsId })
    
    if (response.code === 1000) {
      ElMessage.success('商品删除成功')
      // 重新加载订单数据
      loadOrders()
    } else {
      ElMessage.error(response.message || '删除商品失败')
    }
  } catch (error: any) {
    // 用户取消删除
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error(error)
    }
  }
}

// 删除整个订单
const handleDeleteOrder = async (orderNum: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个订单吗？删除后将无法恢复',
      '删除订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    const response = await deleteOrder({ orderNum })
    
    if (response.code === 1000) {
      ElMessage.success('订单删除成功')
      // 重新加载订单数据
      loadOrders()
    } else {
      ElMessage.error(response.message || '删除订单失败')
    }
  } catch (error: any) {
    // 用户取消删除
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      ElMessage.error(error)
    }
  }
}

// 初始化
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.my-orders-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  background-position: right bottom;
  background-size: contain;
  background-repeat: no-repeat;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #f0f0f0;
}

:deep(.el-tabs__active-bar) {
  height: 3px;
  border-radius: 3px;
  background: linear-gradient(to right, #f56c6c, #e1251b);
}

:deep(.el-tabs__item) {
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #e1251b;
}

:deep(.el-tabs__item:hover) {
  color: #e1251b;
}

.order-item {
  transition: all 0.3s ease;
}

.order-item:hover {
  border-color: #e1251b;
}

.tab-label {
  display: flex;
  align-items: center;
}

/* 订单状态标签样式优化 */
:deep(.el-tag--light.el-tag--danger) {
  color: #f56c6c;
  background-color: #fef0f0;
  border-color: #fde2e2;
}

:deep(.el-tag--light.el-tag--warning) {
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #faecd8;
}

:deep(.el-tag--light.el-tag--primary) {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #d9ecff;
}

:deep(.el-tag--light.el-tag--success) {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

:deep(.el-tag--light.el-tag--info) {
  color: #909399;
  background-color: #f4f4f5;
  border-color: #e9e9eb;
}

/* 按钮效果 */
:deep(.el-button--danger:not(.is-plain):hover),
:deep(.el-button--danger:not(.is-plain):focus) {
  background-color: #c81623;
  border-color: #c81623;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #e1251b;
}

/* 订单卡片美化 */
.order-item {
  border: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
  position: relative;
  overflow: hidden;
}

.order-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.1);
}

/* 已开票订单样式 */
.order-invoiced {
  border: 2px solid #67c23a;
  background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.15);
}

.order-invoiced::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #67c23a, #85ce61);
}

.order-invoiced:hover {
  border-color: #85ce61;
  box-shadow: 0 8px 25px rgba(103, 194, 58, 0.25);
  transform: translateY(-2px);
}

/* 已出库订单样式 */
.order-shipped {
  border: 2px solid #409eff;
  background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.order-shipped::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409eff, #66b1ff);
}

.order-shipped:hover {
  border-color: #66b1ff;
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.25);
  transform: translateY(-2px);
}

.order-header {
  border-bottom: 2px solid #f1f5f9;
  position: relative;
}

/* 已开票订单头部样式 */
.header-invoiced {
  background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%) !important;
  border-bottom: 2px solid #67c23a;
  animation: fadeInGreen 0.5s ease-out;
}

.header-invoiced::after {
  content: '✓ 已开票';
  position: absolute;
  top: 8px;
  right: 12px;
  background: #67c23a;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(103, 194, 58, 0.3);
  animation: slideInRight 0.6s ease-out;
}

/* 已出库订单头部样式 */
.header-shipped {
  background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%) !important;
  border-bottom: 2px solid #409eff;
  animation: fadeInBlue 0.5s ease-out;
}

.header-shipped::after {
  content: '📦 已出库';
  position: absolute;
  top: 8px;
  right: 12px;
  background: #409eff;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
  animation: slideInRight 0.6s ease-out;
}

/* 已出库订单头部样式 */
.header-shipped {
  background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%) !important;
  border-bottom: 2px solid #409eff;
}

.header-shipped::after {
  content: '📦 已出库';
  position: absolute;
  top: 8px;
  right: 12px;
  background: #409eff;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

/* 操作按钮美化 */
.action-btn {
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 状态标签美化 */
:deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
  padding: 4px 12px;
}

/* 商品信息区域美化 */
.product-item {
  transition: all 0.2s ease;
  border-radius: 8px;
}

.product-item:hover {
  background-color: #f8fafc;
  transform: translateX(4px);
}

/* 删除按钮样式 */
.delete-product-btn {
  min-width: 32px;
  height: 32px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.delete-product-btn:hover {
  background-color: #fef0f0;
  border-color: #f56c6c;
  transform: scale(1.05);
}

.product-actions {
  min-width: 40px;
  margin-left: 8px;
}

/* 删除订单按钮样式 */
:deep(.el-button--danger.is-plain) {
  transition: all 0.3s ease;
}

:deep(.el-button--danger.is-plain:hover) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

/* 已删除商品样式 */
.deleted-product {
  background-color: #fef2f2;
  border-left: 4px solid #f56c6c;
  position: relative;
}

.deleted-product::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent 49%, rgba(245, 108, 108, 0.1) 50%, transparent 51%);
  background-size: 10px 10px;
  pointer-events: none;
}

.deleted-tag {
  animation: pulse-red 2s infinite;
}

@keyframes pulse-red {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

@keyframes fadeInGreen {
  from {
    background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
    border-bottom-color: #f1f5f9;
  }
  to {
    background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%);
    border-bottom-color: #67c23a;
  }
}

@keyframes fadeInBlue {
  from {
    background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
    border-bottom-color: #f1f5f9;
  }
  to {
    background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%);
    border-bottom-color: #409eff;
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 已删除商品图片遮罩 */
.product-image .absolute {
  backdrop-filter: blur(1px);
}

/* 已删除商品信息样式 */
.deleted-product .product-name {
  position: relative;
}

.deleted-product .product-name::after {
  content: '已删除';
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f56c6c;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
}

/* 订单备注标签样式 */
.order-remark .el-tag {
  border-radius: 12px;
  font-weight: 500;
  padding: 4px 8px;
}

.order-remark .el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

.order-remark .el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

/* 过滤状态提示样式 */
.filter-status {
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .order-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .order-header .order-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-title h3 {
    font-size: 1rem;
  }
  
  .product-actions {
    margin-left: 4px;
    min-width: 36px;
  }
  
  /* 移动端订单备注标签优化 */
  .order-remark {
    margin-top: 8px;
  }
  
  .order-remark .el-tag {
    font-size: 12px;
    padding: 2px 6px;
  }
  
  /* 移动端订单状态标识优化 */
  .header-invoiced::after,
  .header-shipped::after {
    font-size: 10px;
    padding: 2px 6px;
    top: 4px;
    right: 8px;
  }
  
  /* 移动端订单卡片边框优化 */
  .order-invoiced,
  .order-shipped {
    border-width: 1px;
  }
  
  /* 移动端过滤状态提示优化 */
  .filter-status {
    padding: 8px 12px;
  }
  
  .filter-status .flex {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .filter-status .el-button {
    align-self: flex-end;
  }
}
</style> 